import random
import colorsys

import cv2
import numpy as np


def letterbox_image(image, size):
    """
    给图像添加灰条并resize
    :param image: 需要resize的图像
    :param size: 目标尺寸
    :return: 处理后的图像
    """
    ih, iw = image.shape[:2]
    w, h = size
    scale = min(w / iw, h / ih)
    nw = int(iw * scale)
    nh = int(ih * scale)

    image = cv2.resize(image, (nw, nh))
    new_image = np.ones((h, w, 3), dtype=np.int) * 128
    new_image[(h - nh) // 2: (h - nh) // 2 + nh, (w - nw) // 2: (w - nw) // 2 + nw] = image
    return new_image


def get_n_hls_colors(num):
    """
    获取检测框的颜色
    :param num: 分类数量
    :return: 颜色列表
    """
    hls_colors = []
    i = 0
    step = 360.0 / num
    while i < 360:
        h = i
        s = 90 + random.random() * 10
        l = 50 + random.random() * 10
        _hlsc = [int((h / 360.0) * 255), int((l / 100.0) * 255), int((s / 100.0) * 255)]
        hls_colors.append(_hlsc)
        i += step
    return hls_colors


def get_n_hls_colors_v2(num):
    """
    获取检测框的颜色v2
    参考: https://github.com/bubbliiiing/yolox-pytorch
    :param num: 分类数量
    :return: 颜色列表
    """
    hls_colors = [(x / num, 1., 1.) for x in range(num)]
    colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hls_colors))
    colors = list(map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)), colors))
    return colors
